package com.ruoyi.smart.mqtt.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.smart.mqtt.MessageHandler;
import com.ruoyi.smart.service.DeviceStatusService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * EMQX系统主题处理器
 * 替代原来的EmqxSystemTopicListener，处理设备连接和断开事件
 */
@Slf4j
@Component
public class EmqxSystemTopicHandler implements MessageHandler {

    @Autowired
    private DeviceStatusService deviceStatusService;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public String getTopicFilter() {
        // 同时订阅连接和断开连接主题
        return "$SYS/brokers/+/clients/+/+";
    }

    @Override
    public void handleMessage(String topic, MqttMessage message) {
        String payload = new String(message.getPayload());
        log.debug("收到EMQX系统消息: 主题={}, 内容={}", topic, payload);

        try {
            // 解析JSON消息
            JsonNode jsonNode = objectMapper.readTree(payload);

            // 提取主题的最后一部分来确定事件类型
            String[] topicParts = topic.split("/");
            String lastPart = topicParts[topicParts.length - 1];

            if ("connected".equals(lastPart)) {
                handleClientConnected(jsonNode);
            } else if ("disconnected".equals(lastPart)) {
                handleClientDisconnected(jsonNode);
            } else {
                log.warn("未知的EMQX系统主题: {}", topic);
            }
        } catch (Exception e) {
            log.error("处理EMQX系统消息失败, topic: {}", topic, e);
            // 对于系统主题消息，我们可能不想抛出异常影响其他消息处理
            // 可以根据需要决定是否抛出异常
        }
    }


    /**
     * 处理客户端连接事件
     */
    private void handleClientConnected(JsonNode jsonNode) {
        try {
            String clientId = jsonNode.get("clientid").asText();
            String username = jsonNode.has("username") ?
                    jsonNode.get("username").asText() : "未知用户";
            String ipAddress = jsonNode.has("ipaddress") ?
                    jsonNode.get("ipaddress").asText() : "未知IP";

            log.info("设备上线: clientId={}, username={}, ip={}",
                    clientId, username, ipAddress);

            // 更新设备状态
            deviceStatusService.updateDeviceStatus(clientId, true);
        } catch (Exception e) {
            log.error("解析客户端连接消息失败", e);
            throw new RuntimeException("解析客户端连接消息失败", e);
        }
    }

    /**
     * 处理客户端断开事件
     */
    private void handleClientDisconnected(JsonNode jsonNode) {
        try {
            String clientId = jsonNode.get("clientid").asText();
            String username = jsonNode.has("username") ?
                    jsonNode.get("username").asText() : "未知用户";
            String reason = jsonNode.has("reason") ?
                    jsonNode.get("reason").asText() : "未知原因";

            log.info("设备离线: clientId={}, username={}, reason={}",
                    clientId, username, reason);

            // 更新设备状态
            deviceStatusService.updateDeviceStatus(clientId, false);
        } catch (Exception e) {
            log.error("解析客户端断开消息失败", e);
            throw new RuntimeException("解析客户端断开消息失败", e);
        }
    }
}
